<template>
  <div>
    <el-form label-width="120px">
      <el-form-item label="SPU名称">{{ spuName }}</el-form-item>
      <el-form-item label="SKU名称">
        <el-input
          type="text"
          placeholder="请输入SKU名称"
          v-model="addSkuParams.skuName"
        ></el-input>
      </el-form-item>
      <el-form-item label="价格(元)">
        <el-input
          type="number"
          placeholder="请输入SKU价格"
          v-model="addSkuParams.price"
        ></el-input>
      </el-form-item>
      <el-form-item label="重量(千克)">
        <el-input
          type="number"
          placeholder="请输入SKU重量"
          v-model="addSkuParams.weight"
        ></el-input>
      </el-form-item>
      <el-form-item label="规格描述">
        <el-input
          type="textarea"
          placeholder="请输入SKU描述"
          v-model="addSkuParams.skuDesc"
        ></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form inline>
          <el-form-item
            :label="attr.attrName"
            v-for="(attr, index) in attrInfoList"
            :key="attr.id"
          >
            <el-select placeholder="请选择" v-model="attr.attrInfo">
              <el-option
                :label="attrValue.valueName"
                :value="`${attr.id}:${attrValue.id}`"
                v-for="(attrValue, index) in attr.attrValueList"
                :key="attrValue.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form inline>
          <el-form-item
            :label="saleAttr.saleAttrName"
            v-for="(saleAttr, index) in spuSaleAttrList"
            :key="saleAttr.id"
          >
            <el-select placeholder="请选择" v-model="saleAttr.saleAttrInfo">
              <el-option
                :label="saleAttrValue.saleAttrValueName"
                :value="`${saleAttr.id}:${saleAttrValue.id}`"
                v-for="(saleAttrValue, index) in saleAttr.spuSaleAttrValueList"
                :key="saleAttrValue.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="图片列表">
        <el-table border :data="spuImageList" ref="tableRef">
          <el-table-column type="selection" width="60px" />
          <el-table-column label="图片">
            <template #="{ row, $index }">
              <img :src="row.imgUrl" style="width: 100px; height: 100px" />
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称" />
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                v-if="row.isChecked === 0"
                @click="setDefault(row)"
                >设置为默认值</el-button
              >
              <el-button type="warning" size="small" v-else plain
                >默认</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveSku">保存</el-button>
        <el-button @click="cancelHandler">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick } from "vue";
import { ElMessage } from "element-plus";

import {
  reqAttrInfoList,
  reqSpuSaleAttrList,
  reqSpuImageList,
  reqAddSku,
} from "@/api/product/spu"; // 请求函数
import type {
  IAttrList,
  ISpuSaleAttrList,
  IImageList,
  IAddSkuParams,
  IImage,
  ISkuParams,
} from "@/api/product/spu/model"; // 数据类型

const emit = defineEmits(["changeScene"]);
const attrInfoList = ref<IAttrList>([]); // 商品基础属性列表
const spuSaleAttrList = ref<ISpuSaleAttrList>([]); // spu销售属性
const spuImageList = ref<IImageList>([]); // spu图片列表
const spuName = ref<string>(""); // spu名称
const tableRef = ref(); // table组件实例
const addSkuParams = ref<IAddSkuParams>({
  category3Id: "",
  spuId: "",
  tmId: "",
  skuName: "",
  price: 0,
  weight: "",
  skuDefaultImg: "",
  skuDesc: "",
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
}); // 添加sku所需的参数

// 获取添加SKU所需的数据
const getAddSkuData = async ({ spu, category1Id, category2Id }: ISkuParams) => {
  spuName.value = spu.spuName;
  addSkuParams.value.category3Id = spu.category3Id;
  addSkuParams.value.spuId = spu.id;
  addSkuParams.value.tmId = spu.tmId;

  const attrInfoListData = reqAttrInfoList(
    category1Id,
    category2Id,
    spu.category3Id
  );
  const spuSaleAttrListData = reqSpuSaleAttrList(spu.id);
  const spuImageListData = reqSpuImageList(spu.id);
  const result = await Promise.all([
    attrInfoListData,
    spuSaleAttrListData,
    spuImageListData,
  ]);

  attrInfoList.value = result[0];
  spuSaleAttrList.value = result[1];
  spuImageList.value = result[2];

  spuImageList.value.forEach((item, index) => {
    if (index === 0) {
      item.isChecked = 1;
      nextTick(() => {
        tableRef.value.toggleRowSelection(item, true);
        addSkuParams.value.skuDefaultImg = item.imgUrl;
      });
    } else {
      item.isChecked = 0;
    }
  });
};

// 设置图片默认值
const setDefault = (row: IImage) => {
  spuImageList.value.forEach((item) => {
    item.isChecked = 0;
    tableRef.value.toggleRowSelection(item, false);
  });

  row.isChecked = 1;
  tableRef.value.toggleRowSelection(row, true);
  addSkuParams.value.skuDefaultImg = row.imgUrl;
};

// 添加sku保存按钮的回调
const saveSku = async () => {
  addSkuParams.value.skuAttrValueList = attrInfoList.value.reduce(
    (prev, next) => {
      if (next.attrInfo) {
        const [attrId, valueId]: any = next.attrInfo.split(":");
        prev.push({ attrId, valueId });
      }
      return prev;
    },
    [] as any
  );

  addSkuParams.value.skuSaleAttrValueList = spuSaleAttrList.value.reduce(
    (prev, next) => {
      if (next.saleAttrInfo) {
        const [saleAttrId, saleAttrValueId]: any = next.saleAttrInfo.split(":");
        prev.push({ saleAttrId, saleAttrValueId });
      }
      return prev;
    },
    [] as any
  );

  try {
    await reqAddSku(addSkuParams.value);
    ElMessage({
      type: "success",
      message: "添加成功",
    });
    emit("changeScene", { cutScene: 0 });
  } catch (error) {
    ElMessage({
      type: "error",
      message: "添加失败",
    });
  }
};

// 取消按钮的回调
const cancelHandler = () => {
  clearSkuParamsData();
  emit("changeScene", { cutScene: 0 });
};

// 清空添加SKU所需的数据及参数
const clearSkuParamsData = () => {
  attrInfoList.value = [];
  spuSaleAttrList.value = [];
  spuImageList.value = [];
  addSkuParams.value = {
    category3Id: "",
    spuId: "",
    tmId: "",
    skuName: "",
    price: 0,
    weight: "",
    skuDefaultImg: "",
    skuDesc: "",
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
  };
};

// 对外暴露方法
defineExpose({
  getAddSkuData,
  clearSkuParamsData,
});
</script>
